/**
 * 个人云笔记应用主入口文件
 * Personal Cloud Notes Application Main Entry
 */

const express = require('express');
const path = require('path');
const cors = require('cors');
const helmet = require('helmet');
const compression = require('compression');
const rateLimit = require('express-rate-limit');

// 导入配置和中间件
const config = require('./config/config');
const logger = require('./utils/logger');
const errorHandler = require('./middleware/errorHandler');
const { authMiddleware } = require('./middleware/auth');
const {
  requestPerformanceMiddleware,
  systemResourceMiddleware,
  performanceMetricsHandler,
  resetMetricsHandler,
  healthCheckHandler
} = require('./middleware/performance');

// 导入路由
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/user');
const noteRoutes = require('./routes/notes');
const fileRoutes = require('./routes/files');
const backupRoutes = require('./routes/backup');

const app = express();

// 初始化数据库连接
const { initialize: initDatabase } = require('./database/connection');

// 基础中间件配置
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'", "https://cdn.tailwindcss.com", "https://cdn.jsdelivr.net"],
      scriptSrc: ["'self'", "'unsafe-inline'", "https://cdn.tailwindcss.com"],
      imgSrc: ["'self'", "data:", "https:"],
      fontSrc: ["'self'", "https://cdn.jsdelivr.net"]
    }
  }
}));

app.use(cors({
  origin: process.env.NODE_ENV === 'production' ? false : true,
  credentials: true
}));

// 启用压缩和缓存优化
app.use(compression({
  level: config.cache?.gzipLevel || 6,
  threshold: 1024, // 只压缩大于1KB的响应
  filter: (req, res) => {
    // 不压缩已经压缩的内容
    if (req.headers['x-no-compression']) {
      return false;
    }
    return compression.filter(req, res);
  }
}));

// 静态资源缓存配置
if (config.cache?.enableStaticCache) {
  app.use(express.static(path.join(__dirname, '../public'), {
    maxAge: config.cache.staticCacheMaxAge * 1000,
    etag: true,
    lastModified: true,
    setHeaders: (res, path) => {
      // 为不同类型的文件设置不同的缓存策略
      if (path.endsWith('.html')) {
        res.setHeader('Cache-Control', 'no-cache');
      } else if (path.match(/\.(css|js|png|jpg|jpeg|gif|ico|svg)$/)) {
        res.setHeader('Cache-Control', `public, max-age=${config.cache.staticCacheMaxAge}`);
      }
    }
  }));
} else {
  app.use(express.static(path.join(__dirname, '../public')));
}

// 请求频率限制
const limiter = rateLimit({
  windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000, // 15分钟
  max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100, // 限制每个IP 100个请求
  message: {
    error: '请求过于频繁，请稍后再试 / Too many requests, please try again later'
  },
  standardHeaders: true,
  legacyHeaders: false
});

app.use('/api/', limiter);

// 解析请求体
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 性能监控中间件
app.use(requestPerformanceMiddleware);
app.use(systemResourceMiddleware);

// 请求日志
app.use((req, res, next) => {
  logger.info(`${req.method} ${req.path} - ${req.ip}`);
  next();
});

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/user', authMiddleware, userRoutes);
app.use('/api/notes', authMiddleware, noteRoutes);
app.use('/api/files', authMiddleware, fileRoutes);
app.use('/api/backup', authMiddleware, backupRoutes);

// 健康检查和性能监控端点
app.get('/health', healthCheckHandler);
app.get('/api/admin/metrics', authMiddleware, performanceMetricsHandler);
app.post('/api/admin/metrics/reset', authMiddleware, resetMetricsHandler);

// SPA路由处理 - 只有非API请求返回index.html
app.get('*', (req, res) => {
  // 如果是API请求，返回404错误
  if (req.path.startsWith('/api/')) {
    return res.status(404).json({
      success: false,
      message: 'API端点不存在 / API endpoint not found',
      path: req.path
    });
  }
  
  // 其他请求返回index.html
  res.sendFile(path.join(__dirname, '../public/index.html'));
});

// 错误处理中间件
app.use(errorHandler);

// 启动服务器
const PORT = process.env.PORT || 3000;

async function startServer() {
  try {
    // 初始化数据库连接
    await initDatabase();
    logger.info('数据库连接初始化成功 / Database connection initialized successfully');

    // 启动性能监控
    if (config.performance?.enableMonitoring) {
      const { performanceMonitor } = require('./utils/performance');
      logger.info('性能监控已启用 / Performance monitoring enabled');

      // 设置自定义警告阈值
      if (config.performance.alertThresholds) {
        performanceMonitor.setAlertThresholds(config.performance.alertThresholds);
      }
    }

    // 启动任务调度器
    const scheduler = require('./utils/scheduler');
    scheduler.start();
    logger.info('任务调度器已启动 / Task scheduler started');

    // 启动HTTP服务器
    const server = app.listen(PORT, () => {
      logger.info(`个人云笔记服务器启动成功 / Personal Cloud Notes Server started successfully`);
      logger.info(`服务器地址 / Server URL: http://localhost:${PORT}`);
      logger.info(`环境模式 / Environment: ${process.env.NODE_ENV || 'development'}`);
      logger.info(`性能监控: ${config.performance?.enableMonitoring ? '已启用' : '已禁用'} / Performance monitoring: ${config.performance?.enableMonitoring ? 'enabled' : 'disabled'}`);
    });

    // 设置服务器超时
    server.timeout = 30000; // 30秒超时
    server.keepAliveTimeout = 5000; // 5秒keep-alive超时
    server.headersTimeout = 6000; // 6秒headers超时

    return server;
  } catch (error) {
    logger.error('服务器启动失败 / Server startup failed', {
      error: error.message,
      stack: error.stack
    });
    process.exit(1);
  }
}

startServer();

// 优雅关闭处理
const { close: closeDatabase } = require('./database/connection');

process.on('SIGTERM', async () => {
  logger.info('收到SIGTERM信号，正在关闭服务器... / Received SIGTERM, shutting down server...');

  // 停止任务调度器
  const scheduler = require('./utils/scheduler');
  scheduler.stop();

  await closeDatabase();
  process.exit(0);
});

process.on('SIGINT', async () => {
  logger.info('收到SIGINT信号，正在关闭服务器... / Received SIGINT, shutting down server...');

  // 停止任务调度器
  const scheduler = require('./utils/scheduler');
  scheduler.stop();

  await closeDatabase();
  process.exit(0);
});

module.exports = app;